"use strict"

const db = require("../lib/mysql")
const { success, fail, test } = require("../lib/result")

const showdown = require("showdown"),
  converter = new showdown.Converter()

const turndown = require("turndown")

import cheerio from "cheerio"
import axios from "axios"

const decodeHex2String = function(str) {
  let hex2String = function(hex) {
    let len = hex.length,
      a = new Array(len),
      code
    for (let i = 0; i < len; i++) {
      code = hex.charCodeAt(i)
      if (48 <= code && code < 58) {
        code -= 48
      } else {
        code = (code & 0xdf) - 65 + 10
      }
      a[i] = code
    }

    return String.fromCharCode(
      a.reduce(function(acc, c) {
        acc = 16 * acc + c
        return acc
      }, 0)
    )
  }
  if (str.includes("&#x")) {
    str = str.split("&#x")
    for (let i = 0; i < str.length; i++) {
      if (str[i].includes(";")) {
        let tmp = str[i].split(";")
        str[i] = hex2String(tmp[0]) + tmp[1]
      }
    }
  }
  hex2String = null
  return Array.isArray(str) ? str.join("") : str
}

const get = async function(ctx, next) {
  let query = ctx.request.query || ctx.request.body
  const dic = {
    url: {
      name: "MDN URL",
      type: "String",
      required: true
    }
  }

  const queryResult = test(query, dic)

  if (queryResult.success) {
    query = queryResult.msg
    if (!query.url.includes("https://developer.mozilla.org/")) {
      return fail(25, "MDN URL 不合法")
    }

    // if (
    //   !ctx.request.header ||
    //   !ctx.request.header["user-agent"] ||
    //   !(
    //     ctx.request.header["user-agent"].includes("MicroMessenger") ||
    //     ctx.request.header["user-agent"].includes("miniProgram")
    //   )
    // ) {
    //   return fail(88, "请在全栈小组小程序中打开")
    // }

    let res = await axios.get(query.url)
    if (res.status === 200 && res.data) {
      const $ = cheerio.load(res.data)
      $("article#wikiArticle")
        .find("iframe")
        .each((index, element) => {
          $(element).attr("src", "https://mdn.aside.fun/404.html")
          $(element).removeClass()
        })
      let html = $("article#wikiArticle").html()

      html = html
        .replace(
          new RegExp("https://developer.mozilla.org/", "g"),
          "https://service.aside.fun/api/v1/mdn/article?url=https://developer.mozilla.org/"
        )
        .replace(
          new RegExp('href="/', "g"),
          'href="https://service.aside.fun/api/v1/mdn/article?url=https://developer.mozilla.org/'
        )
        .replace(new RegExp("en-US", "g"), "zh-CN")

      let page = `<!DOCTYPE html>
      <html lang="zh" dir="ltr">
      <head prefix="og: http://ogp.me/ns#">
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <script>(function(d) { d.className = d.className.replace(/\bno-js/, ''); })(document.documentElement);</script>
        <title>MDN 手册</title>
      
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="index, follow">
        <link rel="preload" href="https://developer.mozilla.org/static/fonts/locales/ZillaSlab-Regular.subset.bbc33fb47cf6.woff2" as="font" type="font/woff2"
          crossorigin />
        <link rel="preload" href="https://developer.mozilla.org/static/fonts/locales/ZillaSlab-Bold.subset.e96c15f68c68.woff2" as="font" type="font/woff2"
          crossorigin />
      
        <link rel="home" href="/zh-CN/">
        <link rel="license" href="#license">
        <link href="https://developer.mozilla.org/static/build/styles/react-header.35f24f5aa50c.css" rel="stylesheet" type="text/css" />
        <link href="https://developer.mozilla.org/static/build/styles/react-mdn.95bdccfb6682.css" rel="stylesheet" type="text/css" />
        <link href="https://cdn.bootcss.com/prism/9000.0.1/themes/prism.css" rel="stylesheet" type="text/css" />
        <script src="https://img.meek3n.cn/cdn/prism.js"></script>
        <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
            body {
                width: 100vw;
                overflow-x: hidden;
            }
            .normalPage {
                width: 100vw;
                box-sizing: border-box;
                padding: 22px;
                overflow-x: auto;
            }
        </style>
        </head>
      <body><div class="normalPage">${html}</div>
      <script>
      let arr = document.getElementsByTagName('a')
      for(let i = 0;i < arr.length; i++) {
          if(!arr[i].href.includes('developer.mozilla.org')) {
            arr[i].href = 'javascript: void(0)'
            arr[i].style.color = 'gray'
          }

          if(arr[i].href.includes('https://https://')) {
            arr[i].href = arr[i].href.replace('https://https://', 'https://')
          }
      }
    </script>
    </body>  
      </html>`
      return page
    }
  } else {
    return fail(24, queryResult.msg)
  }
}

const search = async function(ctx, next) {
  let query = ctx.request.query || ctx.request.body
  const dic = {
    name: {
      name: "关键词",
      type: "String",
      required: true
    }
  }

  if (!query.page) {
    query.page = 1
  }

  const queryResult = test(query, dic)

  if (queryResult.success) {
    query = queryResult.msg

    let res = await axios.get(
      `https://developer.mozilla.org/zh-CN/search?q=${query.name}&page=${query.page}`
    )

    if (res.status === 200) {
      const $ = cheerio.load(res.data)
      let list = []
      $(".result-container").each((index, element) => {
        let title = $(element)
            .find("a.result-title")
            .text(),
          url = $(element)
            .find("a.result-title")
            .attr("href"),
          brief = $(element)
            .find("div.result-excerpt")
            .text()

        if (title) {
          list.push({
            title,
            url: "https://developer.mozilla.org" + url,
            brief
          })
        }
      })

      return success(list)
    }

    return success(res)
  } else {
    return fail(22, queryResult.msg)
  }
}

module.exports = {
  search,
  get
}
